package com.csi.bumblebee.service.impl;

import com.csi.bumblebee.domain.user.Student;
import com.csi.bumblebee.domain.vo.LoginVo;
import com.csi.bumblebee.domain.user.Company;
import com.csi.bumblebee.domain.util.MyResult;
import com.csi.bumblebee.domain.util.StateCode;
import com.csi.bumblebee.mapper.CompanyMapper;
import com.csi.bumblebee.service.AccountRoleService;
import com.csi.bumblebee.service.CompanyService;
import com.csi.bumblebee.util.IdUtil;
import com.csi.bumblebee.util.JwtUtil;
import com.csi.bumblebee.util.MD5Utils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.Map;


/**
 * @author 孙伟俊 尹炳顺
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private AccountRoleService accountRoleService;

//    @Qualifier("jdkRedisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CompanyMapper companyMapper;

    /**
     * 展示所有申请过的企业
     * @return List<Company>
     */
    @Override
    public PageInfo<Company> list(int currentPage, int perPageSize) {
        PageHelper.startPage(currentPage, perPageSize);
//        PageInfo pageInfo = new PageInfo<>(companyMapper.list());
        return new PageInfo<>(companyMapper.list());
    }

    /**
     * 根据id查询企业账号
     * @param id company主键id
     * @return
     */
    @Override
    public Company findById(String id) {

        // 从redis取
        Company company = (Company) redisTemplate.opsForValue().get(id);

        // 从mysql取
        if (company ==null){

            company = companyMapper.findById(id);

            // 写入redis
            if (company!=null){
                redisPut(company);
            }
        }

        return company;
    }

    /**
     * 登录
     */
    @Override
    public LoginVo login(Company company) {
        String password = MD5Utils.str2MD5(company.getPassword());
        company.setPassword(password);

        return companyMapper.login(company);
    }

    /**
     * 置空
     */
    @Override
    public int setQualificationNull(String id) {
        return companyMapper.setQualificationNull(id);
    }

    /**
     * 是否有重复
     */
    @Override
    public String findDuplicate(String userName) {
        return companyMapper.findDuplicate(userName);
    }

    /**
     * 注册
     */
    @Override
    public int register(Company company) {
        if(accountRoleService.insertCompany(company.getId()) != 0) {
            return 0;
        }
        String password = MD5Utils.str2MD5(company.getPassword());
        company.setPassword(password);
        company.setCompanyName("恒大");
        return companyMapper.register(company);
    }

    /**
     * 企业端申请
     */
    @Override
    public int application(Company company) {
        int result = companyMapper.application(company);
        company = companyMapper.findByCompanyId(company);

        Company companyTemp = (Company) redisTemplate.opsForValue().get(company.getId());
        if (companyTemp != null){
            if (result > 0){
                redisTemplate.opsForValue().set(company.getId(), company);
            }else {
                redisTemplate.opsForValue().set(companyTemp.getId(), companyTemp);
            }
        }
        return result;
    }

    /**
     * 展示所有在申请的企业
     * @return List<Company>
     */
    @Override
    public List<Company> listApplyCompany() {
            return companyMapper.listApplyCompany();
    }

    /**
     * 后台增加新企业
     * @param company 对象
     * @return 影响行数
     */
    @Override
    public int add(Company company) {
        company.setId(IdUtil.getString(Company.PRE_NAME));

        int result = companyMapper.add(company);
        if (result > 0){
            redisTemplate.opsForValue().set(company.getId(), company);
        }
        return result;
    }

    /**
     * 后台更新企业信息
     * @param company 企业对象
     * @return 影响行数
     */
    @Override
    public int update(Company company) {
        int result = companyMapper.update(company);
        company = companyMapper.findById(company.getId());

        if (result > 0) {
            redisTemplate.opsForValue().set(company.getId(), company);
        }
        return result;
    }

    /**
     * 从后台删除一个公司
     * @param id 主键
     * @return 影响行数
     */
    @Override
    public int delete(String id) {

        int result = companyMapper.delete(id);
        if (result > 0) {
            redisTemplate.delete(id);
        }
        return result;
    }

    /**
     * 审核通过
     * @param map map
     * @return 影响行数
     */
    @Override
    public int updatePass(Map<String, Object> map) {
        int result = companyMapper.updatePass(map);
        Company company = (Company) redisTemplate.opsForValue().get(map.get("id"));
        if (company == null) {
            company = companyMapper.findById((String) map.get("id"));
            redisTemplate.opsForValue().set((String) map.get("id"), company);
        }
        return result;
    }

    /**
     * 审核不通过
     * @param map map
     * @return 影响行数
     */
    @Override
    public int updateNotPass(Map<String, Object> map) {
        int result = companyMapper.updateNotPass(map);
        Company company = (Company) redisTemplate.opsForValue().get((String)map.get("id"));
        if (company != null) {
            redisTemplate.delete((String)map.get("id"));
        }
        return result;
    }

    @Override
    public int accountDestroy(String id) {
        return companyMapper.accountDestroy(id);
    }

    @Override
    public boolean updateCompany(Company company) {
        boolean result = false;

        // 删除redis
        Company companyRedis = redisDelete(company.getId());

        // mysql更新
        if (companyMapper.updateCompany(company) == 1) {

            // 更新redis
            redisPut(companyMapper.findById(company.getId()));
            result = true;

            // 放回redis老数据
        } else {
            redisPut(companyRedis);
        }
        return result;
    }

    /**
     * 判断是否通过申请
     */
    public MyResult<LoginVo> isPassApplication(LoginVo loginVO){

        MyResult<LoginVo> myResult = new MyResult<>();

        if (loginVO.getStatus() == 1){
            myResult.setCode(StateCode.PASSAPPLICATION);
            myResult.setMessage("正在审核中");
            return myResult;
        }else if (loginVO.getStatus() == 2){
            myResult.setCode(StateCode.PASSAPPLICATION_SUCCESS);
            myResult.setMessage("审核成功,即将进入登录界面");
            myResult.setData(loginVO);
            return myResult;
        }else {
            myResult.setCode(StateCode.PASSAPPLICATION_FAILURE);
            myResult.setMessage("审核失败");
            setQualificationNull(loginVO.getId());
            return myResult;
        }
    }

    /**
     * 放入redis
     *
     * @param company Company对象
     */
    private void redisPut(Company company) {
        redisTemplate.opsForValue().set(company.getId(), company
                /*, getExpireTime()*/);
    }

    /**
     * 从redis取数据
     *
     * @param id 学生id
     * @return Company对象
     */
    private Company redisGet(String id) {
        /*redisTemplate.expire(id, getExpireTime(), TimeUnit.SECONDS);*/
        return (Company) redisTemplate.opsForValue().get(id);
    }

    /**
     * 从redis删除
     *
     * @param id company id
     * @return 删除的company
     */
    private Company redisDelete(String id) {
        Company company = redisGet(id);
        redisTemplate.delete(id);
        return company;
    }

    private long getExpireTime() {
        return 60 * 60 * 24 * 7;
    }
}
